package com.yy.wga.common.util.mapping;

import cn.hutool.core.bean.BeanUtil;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * bean 工具类
 *
 * @author <a href="mailto:ludezheng@hongrz.com"> ludezh </a>
 * @version 1.0.0   2018/10/7,15:43
 * @since 1.0.0     2018/10/7,15:43
 */
@Slf4j
public class BeansUtils extends BeanUtils {

    /**
     * 基于Dozer转换对象的类型.
     */
    public static <T> T map(Object source, Class<T> destinationClass) {
        return BeanUtil.toBeanIgnoreError(source, destinationClass);
    }

    /**
     * 基于Dozer转换Collection中对象的类型.
     */
    @SuppressWarnings("rawtypes")
    public static <T> List<T> mapList(Collection sourceList, Class<T> destinationClass) {
        if (sourceList == null) {
            return Collections.emptyList();
        }
        List<T> destinationList = Lists.newArrayList();
        for (Object sourceObject : sourceList) {
            T destinationObject = BeanUtil.toBeanIgnoreError(sourceObject, destinationClass);
            destinationList.add(destinationObject);
        }
        return destinationList;
    }

    /**
     * 基于Dozer将对象A的值拷贝到对象B中.
     */
    public static void copy(Object source, Object destinationObject) {
        BeanUtil.copyProperties(source, destinationObject);
    }

    /**
     * bean to Map<String,Object>
     * 对象转为map
     *
     * @param obj
     * @return Map<String, Object>
     * @throws Exception
     */
    public static Map<String, Object> toMapObject(Object obj) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor property : propertyDescriptors) {
            String key = property.getName();
            // 过滤class属性
            if (!key.equals("class")) {
                // 得到property对应的getter方法
                Method getter = property.getReadMethod();
                if (getter == null) {
                    continue;
                }
                Object val = getter.invoke(obj);
                map.put(key, val);
            }

        }
        return map;
    }

}
